package com.ibeetl.admin.core.rbac.tree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ibeetl.admin.core.entity.CoreArea;

public class AreaItem  implements TreeItem{
	CoreArea sysArea = null;
	List<AreaItem> children = new ArrayList<AreaItem>();
	@JsonIgnore
	AreaItem parent = null;
	String name;
	private Integer seq;
	public AreaItem(CoreArea sysArea){
		this.sysArea = sysArea;
		this.name = sysArea!=null?sysArea.getName():null;
		this.seq = sysArea.getSeq();
	}
	
	
	public void setParent(AreaItem parent){
		this.parent = parent;
		parent.children.add(this);
	}
	
	public List<AreaItem> getChildren(){
		return this.children;
	}
	
	public Long getAreaCode() {
		return sysArea.getAreaCode();
	}
	public Long getId(){
		return sysArea.getId();
	}
	
	public CoreArea getData(){
		return this.sysArea;
	}
	
	
	public void filter(Set<Long> allows){
		Iterator<AreaItem> it = this.children.iterator();
		while(it.hasNext()){
			AreaItem item = it.next();
			if(item.getChildren().size()==0&&!allows.contains(item.getData().getId())){
				it.remove();
			}
			
			if(item.getChildren().size()!=0){
				item.filter(allows);
				if(item.getChildren().size()==0){
					it.remove();
				}
			}
			
			
		
		}
		
	}
	
	
	/**
	 * 查找某个指定的子功能
	 * @param functionId
	 * @return
	 */
	public AreaItem findChild(Long areaId){
		if(sysArea.getId().equals(areaId)){
			return this;
		}
		for(AreaItem item:children){
			AreaItem find = item.findChild(areaId);
			if(find!=null){
				return find;
			}
		}
		return null;
		
	}
	
	/**
	 * 查找所有的子栏目
	 * @return
	 */
	public List<AreaItem> findAllItem(){
		List<AreaItem> all = new LinkedList<>();
		findAllChildItem(all,this);
		return all;
	}
	
	
	private void findAllChildItem(List<AreaItem> all,AreaItem parent){
		for(AreaItem item:parent.children){
			all.add(item);
			findAllChildItem(all,item);
		}
		
	}
	


	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((sysArea == null) ? 0 : sysArea.hashCode());
		return result;
	}


	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AreaItem other = (AreaItem) obj;
		if (sysArea == null) {
			if (other.sysArea != null)
				return false;
		} else if (!sysArea.equals(other.sysArea))
			return false;
		return true;
	}


	public AreaItem getParent() {
		return parent;
	}


	@Override
	public String toString() {
		return "AreaItem [sysArea=" + sysArea.getName() + ","+this.children.size()+"]";
	}


	@Override
	public String getName() {
		return this.name;
	}


	public Integer getSeq() {
		return seq;
	}


	public void setSeq(Integer seq) {
		this.seq = seq;
	}



	
	
	
	

}
